package com.lizhi.yun.base.context;/**
 * @program: sfrobot-html
 * @name SpringContextUtil
 * @description:
 * @author: lizhi
 * @create: 2020-04-23 15:12
 */

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 *@program: sfrobot-html
 *@name SpringContextUtil
 *@description:
 *@author: lizhi
 *@create: 2020-04-23 15:12
 */
@Component
public class SpringContextUtil implements ApplicationContextAware, BeanFactoryPostProcessor {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext args) throws BeansException {
        applicationContext = args;
    }

    public static <T> T getBean(Class<T> clazz){
        return applicationContext.getBean(clazz);
    }

    public static <T> T getBean(String beanName, Class<T> clazz) {
        return applicationContext.getBean(beanName, clazz);
    }

    public static <T> Map<String, T> getBeans(Class<T> clazz) {
        return applicationContext.getBeansOfType(clazz);
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        beanFactory.getBean(SpringContextUtil.class);
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}
